package cn.ckx.coding.common.dto;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiParam;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang.StringUtils;

import java.util.Optional;


@ApiModel(description = "分页排序")
@Data
@EqualsAndHashCode(callSuper = true)
public class Sortable extends Pageable {

    @ApiParam("排序字段")
    private String orderField;

    @ApiParam("排序方向：ASC-升序,DESC-降序")
    private Order order;

    @Override
    public <T> IPage<T> toPage() {
        Page<T> pager = (Page<T>) super.toPage();
        if (StringUtils.isNotBlank(orderField)) {
            pager.addOrder(Order.ASC.equals(Optional.ofNullable(order).orElse(Order.ASC))?OrderItem.asc(orderField):OrderItem.desc(orderField));
        }
        return pager;    
    }

    /**
     * 排序方向
     */
    public enum Order{
        /**
         * 升序
         */
        ASC("asc"),

        /**
         * 降序
         */
        DESC("desc");
        
        Order(String code){
            this.code = code;     
        }
        
        private String code;

        public String getCode() {
            return code;
        }
    } 
}
